<template>
  <el-container>
    <el-header>
      <navigation @adminLogin="getNavData" ref="navigation" :activeIndex="'/admin'"></navigation>
    </el-header>
    <el-container>
      <!-- 左侧导航栏 -->
      <el-aside width="250px">
        <el-row class="tac">
          <el-col>
            <el-menu
              @select="handleSelect"
              :default-active="actionIndex"
              class="el-menu-vertical-demo"
            >
              <el-menu-item index="1">
                <i class="el-icon-s-home"></i>
                <span slot="title">题库管理</span>
              </el-menu-item>
              <el-menu-item index="2">
                <i class="el-icon-s-custom"></i>
                <span slot="title">班级管理</span>
              </el-menu-item>
              <el-menu-item index="3">
                <i class="el-icon-reading"></i>
                <span slot="title">考试管理</span>
              </el-menu-item>
            </el-menu>
          </el-col>
        </el-row>
      </el-aside>
      <el-container>
        <!-- 内容框 -->
        <el-main>
          <!-- 题库表格 -->
          <div v-if="this.actionIndex == '1'">
            <el-table stripe :data="pageData.data" style="width: 100%">
              <el-table-column prop="bankId" label="序号" width="180"></el-table-column>
              <el-table-column prop="bankName" label="题库名字" width="180"></el-table-column>
              <el-table-column prop="bankCreteTime" label="创建时间" width="180"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <!-- 管理题目 -->
                  <el-button
                    type="primary"
                    @click="goQuestion(scope.$index, scope.row)"
                    size="small"
                    round
                  >管理题目</el-button>
                  <!-- 修改按钮 -->
                  <el-button
                    type="success"
                    @click="handEdit(scope.$index, scope.row)"
                    size="small"
                    round
                  >修改</el-button>
                  <!-- 删除按钮 -->
                  <el-popconfirm @onConfirm="handDelete(scope.$index, scope.row)" title="是否删除该题库?">
                    <el-button
                      size="small"
                      style="margin: 10px"
                      slot="reference"
                      type="danger"
                      icon="el-icon-delete"
                      circle
                    ></el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 具体某个题库内容 -->
          <div v-else-if="this.actionIndex == '1-1'">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <el-page-header
                  @back="actionIndex = '1'"
                  :content="this.questionData.bankData.bankName"
                ></el-page-header>
              </div>
              <el-table stripe :data="questionData.questionType" style="width: 100%">
                <el-table-column prop="typeId" label="序号" width="180"></el-table-column>
                <el-table-column prop="typeName" label="题目类型" width="180"></el-table-column>
                <el-table-column prop="count" label="数量" width="180"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <!-- 管理题目 -->
                    <el-button
                      type="primary"
                      @click="goQuestion(scope.$index, scope.row)"
                      size="small"
                      round
                    >管理题目</el-button>
                    <!-- 修改按钮 -->
                    <el-button
                      type="success"
                      @click="handEdit(scope.$index, scope.row)"
                      size="small"
                      round
                    >修改</el-button>
                    <!-- 删除按钮 -->
                    <el-popconfirm
                      @onConfirm="handDelete(scope.$index, scope.row)"
                      title="是否删除该类型及其包含的题目?"
                    >
                      <el-button
                        size="small"
                        style="margin: 10px"
                        slot="reference"
                        type="danger"
                        icon="el-icon-delete"
                        circle
                      ></el-button>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
          <!-- 班级表格 -->
          <div v-else-if="this.actionIndex == '2'">
            <el-table stripe :data="pageData.data" style="width: 100%">
              <el-table-column prop="id" label="序号" width="180"></el-table-column>
              <el-table-column prop="name" label="班级" width="180"></el-table-column>
              <el-table-column prop="count" label="人数" width="180"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <!-- 管理班级按钮 -->
                  <el-button
                    @click="handManageClass(scope.$index, scope.row)"
                    type="primary"
                    size="small"
                    round
                  >管理班级</el-button>
                  <!-- 修改按钮 -->
                  <el-button
                    type="success"
                    @click="handEditClass(scope.$index, scope.row)"
                    size="small"
                    round
                  >修改</el-button>
                  <!-- 删除按钮 -->
                  <el-popconfirm
                    @onConfirm="handDeleteClass(scope.$index, scope.row)"
                    title="是否删除该班级?"
                  >
                    <el-button
                      size="small"
                      style="margin: 10px"
                      slot="reference"
                      type="danger"
                      icon="el-icon-delete"
                      circle
                    ></el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 具体某个班级学生 -->
          <div v-else-if="this.actionIndex == '2-1'">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <el-page-header
                  @back="actionIndex = '2';getClassData('1')"
                  :content="this.editClassName"
                ></el-page-header>
              </div>
              <el-table stripe :data="pageData.data" style="width: 100%">
                <el-table-column prop="userId" label="账号" width="180"></el-table-column>
                <el-table-column prop="name" label="班级" width="180"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <!-- 删除按钮 -->
                    <el-popconfirm
                      @onConfirm="handDeleteStudent(scope.$index, scope.row)"
                      title="是否将该学生从班级中删除?"
                    >
                      <el-button
                        size="small"
                        style="margin: 10px"
                        slot="reference"
                        type="danger"
                        icon="el-icon-delete"
                        circle
                      ></el-button>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
          <!-- 考试管理 -->
          <div v-else>考试管理</div>
        </el-main>
        <!-- 页脚 -->
        <el-footer>
          <!-- 分页条 -->
          <el-pagination
            v-if="this.actionIndex != '1-1'"
            background
            layout="prev, pager, next"
            :current-page="this.pageData.index"
            :page-size="this.pageData.pageSize"
            :total="this.pageData.total"
            @current-change="changeIndex"
          ></el-pagination>
          <!-- 添加考试按钮 -->
          <el-button
            v-if="this.actionIndex == '1'"
            @click="addExamFormVisible = true"
            type="primary"
            round
          >添加考试</el-button>
          <!-- 添加考试按钮 -->
          <el-button
            v-else-if="this.actionIndex == '2'"
            @click="addClassFormVisible = true"
            type="primary"
            round
          >添加班级</el-button>
          <!-- 添加学生 -->
          <div v-else-if="this.actionIndex == '2-1'">
            <el-button
              style="margin: 5px"
              @click="addStudentFormChoiceVisible = true"
              type="primary"
              round
            >添加学生</el-button>
          </div>
        </el-footer>
      </el-container>
    </el-container>

    <!-- 修改题库输入框 -->
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      title="修改题库"
      :visible.sync="editExamFormVisible"
      :show-close="false"
    >
      <el-form :model="examFormData" :rules="rules3" ref="editExamForm">
        <el-form-item label="题库名字" :label-width="formLabelWidth" prop="bankName">
          <el-input v-model="examFormData.bankName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editExamForm')">取 消</el-button>
        <el-button type="primary" @click="editExamSubmit">修 改</el-button>
      </div>
    </el-dialog>

    <!-- 添加考试输入框 -->
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      title="创建题库"
      :visible.sync="addExamFormVisible"
      :show-close="false"
    >
      <el-form :model="examFormData" :rules="rules3" ref="addExamForm">
        <el-form-item label="题库名字" :label-width="formLabelWidth" prop="bankName">
          <el-input v-model="examFormData.bankName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('addExamForm')">取 消</el-button>
        <el-button type="primary" @click="addExamSubmit">创 建</el-button>
      </div>
    </el-dialog>

    <!-- 添加班级输入框 -->
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      title="创建班级"
      :visible.sync="addClassFormVisible"
      :show-close="false"
    >
      <el-form :model="classFormData" :rules="rules4" ref="addClassForm">
        <el-form-item label="班级名字" :label-width="formLabelWidth" prop="name">
          <el-input v-model="classFormData.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('addClassForm')">取 消</el-button>
        <el-button type="primary" @click="addClassSubmit">创 建</el-button>
      </div>
    </el-dialog>

    <!-- 修改班级输入框 -->
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      title="修改班级"
      :visible.sync="editClassFormVisible"
      :show-close="false"
    >
      <el-form :model="classFormData" :rules="rules4" ref="editClassForm">
        <el-form-item label="班级名字" :label-width="formLabelWidth" prop="name">
          <el-input v-model="classFormData.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editClassForm')">取 消</el-button>
        <el-button type="primary" @click="editClassSubmit">修 改</el-button>
      </div>
    </el-dialog>

    <!-- 添加学生选择对话框 -->
    <el-dialog
      title="选择"
      :visible.sync="addStudentFormChoiceVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-button
        style="margin: 5px"
        @click="addStudentFormChoiceVisible = false;addStudentFormVisible = true"
        type="primary"
        round
      >手动添加学生</el-button>
      <el-upload
        class="upload-demo"
        action="https://jsonplaceholder.typicode.com/posts/"
        :on-preview="handlePreview"
        multiple
        :on-exceed="handleExceed"
      >
        <el-button size="small" type="primary">使用Excel导入</el-button>
        <div slot="tip" class="el-upload__tip">只能上传.xls文件</div>
      </el-upload>
    </el-dialog>

    <!-- 添加学生输入框 -->
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      title="添加学生"
      :visible.sync="addStudentFormVisible"
      :show-close="false"
    >
      <el-form :model="studentFormData" :rules="rules5" ref="addStudentForm">
        <el-form-item label="学生学号" :label-width="formLabelWidth" prop="userId">
          <el-input v-model="studentFormData.userId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生名字" :label-width="formLabelWidth" prop="name">
          <el-input v-model="studentFormData.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('addStudentForm')">取 消</el-button>
        <el-button type="primary" @click="addStudentSubmit">添 加</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
export default {
  name: "admin",
  data() {
    return {
      location: "http://localhost:8866",
      actionIndex: "1",
      addExamFormVisible: false,
      editExamFormVisible: false,
      addClassFormVisible: false,
      editClassFormVisible: false,
      addStudentFormVisible: false,
      addStudentFormChoiceVisible: false,
      formLabelWidth: "80px",
      editBankId: "",
      editClassId: "",
      editClassName: "",
      examFormData: {
        bankName: "",
      },
      classFormData: {
        name: "",
      },
      studentFormData: {
        userId: "",
        name: "",
      },
      rules3: {
        bankName: [
          {
            required: true,
            message: "题库名字不许为空",
            trigger: "blur",
          },
        ],
      },
      rules4: {
        name: [
          {
            required: true,
            message: "班级名字不许为空",
            trigger: "blur",
          },
        ],
      },
      rules5: {
        userId: [
          {
            required: true,
            message: "学生账号不许为空",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "学生名字不许为空",
            trigger: "blur",
          },
        ],
      },
      pageData: {
        data: [],
        index: 1,
        total: 1,
        pageSize: 1,
        pages: 1,
        isFirstPage: true,
        isLastPage: false,
      },
      questionData: {
        questionType: [],
        bankData: [],
        questionList: [],
      },
    };
  },
  created() {
    this.getBankData("1");
  },
  methods: {
    // 获取子组件的值,用来判断是否是管理员登录
    getNavData(data) {
      if (!data) {
        this.$router.push("/");
        this.$message({
          type: "warning",
          message: "您不是教师，无法进行操作",
          duration: 1000,
        });
      }
    },

    // 服务器错误消息提示
    errorMessage() {
      this.$message({
        type: "error",
        message: "服务器出现问题，请稍后重新尝试",
        duration: 1000,
      });
    },

    // 时间处理
    getTime(time) {
      const dateTime = new Date(time);
      const year = dateTime.getFullYear();
      const month = dateTime.getMonth() + 1;
      const date = dateTime.getDate();
      const hour = dateTime.getHours();
      const minute = dateTime.getMinutes();
      const second = dateTime.getSeconds();
      return (
        year +
        "-" +
        this.addZero(month) +
        "-" +
        this.addZero(date) +
        " " +
        this.addZero(hour) +
        ":" +
        this.addZero(minute) +
        ":" +
        this.addZero(second)
      );
    },

    // 时间显示处理
    addZero(v) {
      return v < 10 ? "0" + v : v;
    },

    // 左侧导航栏点击事件
    handleSelect(key, keypath) {
      this.actionIndex = key;
      switch (key) {
        case "1":
          this.getBankData("1");
          break;
        case "2":
          this.getClassData("1");
          break;
        case "3":
          break;
      }
    },

    // 关闭对话框
    resetForm(formName) {
      if (formName == "addExamForm") {
        this.addExamFormVisible = false;
      } else if (formName == "editExamForm") {
        this.editExamFormVisible = false;
      } else if (formName == "editClassForm") {
        this.editClassFormVisible = false;
      } else if (formName == "addClassForm") {
        this.addClassFormVisible = false;
      } else if (formName == "addStudentForm") {
        this.addStudentFormVisible = false;
      }
      this.$refs[formName].resetFields();
    },

    // 页码变动函数
    changeIndex(index) {
      switch (this.actionIndex) {
        case "1":
          this.getBankData(index);
          break;
        case "2":
          this.getClassData(index);
          break;
        case "2-1":
          this.getStudentData(index);
          break;
      }
    },

    /***************************************** 题库部分函数 ***********************************/
    // 添加题库请求
    addExamSubmit() {
      this.$refs["addExamForm"].validate((valid) => {
        if (valid) {
          const formdata = new FormData();
          formdata.append("bankName", this.examFormData.bankName);
          this.axios
            .post(this.location + "/bank", formdata)
            .then((res) => {
              console.log(res);
              if (res.data.code == 100) {
                this.$message({
                  type: "success",
                  message: "题库创建成功",
                  duration: 1000,
                });
                this.getBankData(this.pageData.pages + 1);
                this.resetForm("addExamForm");
              } else if (res.data.code == 200) {
                this.$message({
                  type: "warning",
                  message: res.data.msg,
                  duration: 1000,
                });
              }
            })
            .catch((err) => {
              console.error(err);
              this.errorMessage();
            });
        }
      });
    },

    // 点击题库删除
    handDelete(index, row) {
      console.log("删除题库" + index);
      this.axios
        .delete(this.location + "/bank/" + row.bankId)
        .then((res) => {
          console.log(res);
          if (res.data.code == 100) {
            this.$message({
              type: "success",
              message: "删除成功",
              duration: 1000,
            });
            this.getBankData(this.pageData.index);
          } else {
            this.$message({
              type: "warning",
              message: res.data.msg,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          console.error(err);
          this.errorMessage();
        });
    },

    // 点击题库修改
    handEdit(index, row) {
      console.log(index, row);
      this.editExamFormVisible = true;
      this.examFormData.bankName = row.bankName;
      this.editBankId = row.bankId;
    },

    // 获取题库数据
    getBankData(index) {
      this.axios
        .get(this.location + "/bank/" + index + "?size=7")
        .then((res) => {
          console.log(res);
          if (res.data.code == 100) {
            this.pageData = res.data.extend.bankPageData;
            for (var i = 0; i < this.pageData.data.length; i++) {
              this.pageData.data[i].bankCreteTime = this.getTime(
                this.pageData.data[i].bankCreteTime
              );
            }
          } else if (res.data.code == 200) {
            this.$message({
              type: "warning",
              message: res.data.msg,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          console.error(err);
          this.errorMessage();
        });
    },

    // 修改题库请求
    editExamSubmit() {
      this.$refs["editExamForm"].validate((valid) => {
        if (valid) {
          const formdata = new FormData();
          formdata.append("bankId", this.editBankId);
          formdata.append("bankName", this.examFormData.bankName);
          this.axios
            .put(this.location + "/bank", formdata, {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            })
            .then((res) => {
              console.log(res);
              if (res.data.code == 100) {
                this.$message({
                  type: "success",
                  message: res.data.msg,
                  duration: 1000,
                });
                this.getBankData(this.pageData.index);
                this.resetForm("editExamForm");
              } else if (res.data.code == 200) {
                this.$message({
                  type: "warning",
                  message: res.data.msg,
                  duration: 1000,
                });
              }
            })
            .catch((err) => {
              console.error(err);
              this.errorMessage();
            });
        }
      });
    },

    // 进入某个题库中
    goQuestion(index, row) {
      this.actionIndex = "1-1";
      this.questionData.bankData = row;
      this.axios
        .get(this.location + "/bank/data/" + row.bankId)
        .then((res) => {
          console.log(res);
          if (res.data.code == 100) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1000,
            });
            this.questionData.questionType =
              res.data.extend.questionData.questionType;
            this.questionData.questionList =
              res.data.extend.questionData.questions;
          }
        })
        .catch((err) => {
          console.error(err);
          this.errorMessage();
        });
    },

    /***************************************** 班级部分函数 ***********************************/
    // 点击班级修改
    handEditClass(index, row) {
      console.log(index, row);
      this.editClassFormVisible = true;
      this.classFormData.name = row.name;
      this.editClassId = row.id;
    },

    // 点击管理班级
    handManageClass(index, row) {
      console.log(index, row);
      this.editClassId = row.id;
      this.actionIndex = "2-1";
      this.editClassName = row.name;
      this.getStudentData("1");
    },

    // 获取班级数据
    getClassData(index) {
      this.axios
        .get(this.location + "/class/" + index + "?size=7")
        .then((res) => {
          console.log(res);
          if (res.data.code == 100) {
            this.pageData = res.data.extend.classPageData;
          } else if (res.data.code == 200) {
            this.$message({
              type: "warning",
              message: res.data.msg,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          console.error(err);
          this.errorMessage();
        });
    },

    // 获取班级中学生的信息
    getStudentData(index) {
      this.axios
        .get(
          this.location +
            "/user/" +
            index +
            "?size=6&classId=" +
            this.editClassId
        )
        .then((res) => {
          console.log(res);
          if (res.data.code == 100) {
            this.pageData = res.data.extend.studentPageData;
          } else if (res.data.code == 200) {
            this.$message({
              type: "warning",
              message: res.data.msg,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          console.error(err);
          this.errorMessage();
        });
    },

    // 添加班级请求
    addClassSubmit() {
      this.$refs["addClassForm"].validate((valid) => {
        if (valid) {
          const formdata = new FormData();
          formdata.append("name", this.classFormData.name);
          this.axios
            .post(this.location + "/class", formdata)
            .then((res) => {
              console.log(res);
              if (res.data.code == 100) {
                this.$message({
                  type: "success",
                  message: res.data.msg,
                  duration: 1000,
                });
                this.getClassData(this.pageData.pages + 1);
                this.resetForm("addClassForm");
              } else if (res.data.code == 200) {
                this.$message({
                  type: "warning",
                  message: res.data.msg,
                  duration: 1000,
                });
              }
            })
            .catch((err) => {
              console.error(err);
              this.errorMessage();
            });
        }
      });
    },

    // 添加学生请求
    addStudentSubmit() {
      this.$refs["addStudentForm"].validate((valid) => {
        if (valid) {
          const formdata = new FormData();
          formdata.append("userId", this.studentFormData.userId);
          formdata.append("name", this.studentFormData.name);
          formdata.append("classId", this.editClassId);
          this.axios
            .post(this.location + "/user", formdata)
            .then((res) => {
              console.log(res);
              if (res.data.code == 100) {
                this.$message({
                  type: "success",
                  message: res.data.msg,
                  duration: 1000,
                });
                this.getStudentData(this.pageData.index);
                this.resetForm("addStudentForm");
              } else {
                this.$message({
                  type: "warning",
                  message: res.data.msg,
                  duration: 1000,
                });
              }
            })
            .catch((err) => {
              console.error(err);
              this.errorMessage();
            });
        }
      });
    },

    // 修改班级请求
    editClassSubmit() {
      const formdata = new FormData();
      formdata.append("id", this.editClassId);
      formdata.append("name", this.classFormData.name);
      this.axios
        .put(this.location + "/class", formdata, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          console.log(res);
          if (res.data.code == 100) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1000,
            });
            this.getClassData(this.pageData.index);
            this.resetForm("editClassForm");
          } else if (res.data.code == 200) {
            this.$message({
              type: "warning",
              message: res.data.msg,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          console.error(err);
          this.errorMessage();
        });
    },

    // 删除班级请求
    handDeleteClass(index, row) {
      this.axios
        .delete(this.location + "/class/" + row.id)
        .then((res) => {
          console.log(res);
          if (res.data.code == 100) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1000,
            });
            this.getClassData(this.pageData.index);
          } else if (res.data.code == 200) {
            this.$message({
              type: "warning",
              message: res.data.msg,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },

    // 删除某个学生请求
    handDeleteStudent(index, row) {
      this.axios
        .delete(this.location + "/user/" + row.userId)
        .then((res) => {
          console.log(res);
          if (res.data.code == 100) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1000,
            });
            this.getStudentData(this.pageData.index);
          }
        })
        .catch((err) => {
          console.error(err);
          this.errorMessage();
        });
    },

    //
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}
</style>